import axios from 'axios'
import store from '@/store'
import router from '@/router'
// MessageBox
import {Message} from 'element-ui'
import {getToken} from '@/utils/auth'

// console.log(process.env)
const service = axios.create({
    //  baseURL: process.env.NODE_ENV == 'development' ? '/home' : 'http://192.168.1.2:8082/api/',// process.env.VUE_APP_BASE_API, // url = base url + request url
    baseURL: process.env.VUE_APP_BASE_API,
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 50000 // request timeout
})

service.interceptors.request.use(
    config => {
        if (store.getters.token) {
            config.headers['Like-admin'] = getToken()
        }
        return config
    },


    error => {
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        const res = response.data
        if (response.status === 200 && response.config.url === "gui/work/snapExcel") {
            return res
        }
        if (response.status === 200 && response.config.url === "user/flow/excel") {
            return res
        }
        if (response.status === 200 && response.config.url === "user/duration/excel") {
            return res
        }
        if (response.status === 200 && response.config.url === "user/count/excel") {
            return res
        }
        if (res.code !== 200) {
            Message({
                message: res.msg || 'Error',
                type: 'error',
                duration: 5 * 1000
            })

            if (res.code === 333 || res.code === 332 || res.code === 331) {
                // to re-login
                store.dispatch('user/resetToken').then(() => {
                    router.push(`/login?code=${res.code}`)
                })
            }
            // return Promise.reject(new Error(res.message || 'Error'))
            return res
        } else {
            return res
        }
    },
    error => {
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return error
        // return Promise.reject(error)
    }
)

export default service
